﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;

namespace HYLightingEquipmentLay.CommonUtils
{
	public class LevelUtils
	{
		public static bool GetUpMostNearLevel(Autodesk.Revit.DB.Document doc, double dPrjElevation, out Level outLevel)
		{
			bool result = false;
			try
			{
				List<Level> specifyElements = DocumentElementUtils.GetSpecifyElements<Level>(doc);
				SortedDictionary<double, Level> sortedDictionary = new SortedDictionary<double, Level>();
				foreach (Level level in specifyElements)
				{
					double projectElevation = level.ProjectElevation;
					if (projectElevation > dPrjElevation)
					{
						double key = Math.Abs(projectElevation - dPrjElevation);
						if (!sortedDictionary.ContainsKey(key))
						{
							sortedDictionary.Add(key, level);
						}
					}
				}
				if (sortedDictionary.Count > 0)
				{
					outLevel = sortedDictionary.First<KeyValuePair<double, Level>>().Value;
					result = true;
				}
				else
				{
					outLevel = null;
				}
			}
			catch
			{
				outLevel = null;
			}
			return result;
		}

		public static bool GetMostNearLevel(Autodesk.Revit.DB.Document doc, double dPrjElevation, out Level outLevel)
		{
			bool result = false;
			try
			{
				List<Level> specifyElements = DocumentElementUtils.GetSpecifyElements<Level>(doc);
				SortedDictionary<double, Level> sortedDictionary = new SortedDictionary<double, Level>();
				foreach (Level level in specifyElements)
				{
					double key = Math.Abs(level.ProjectElevation - dPrjElevation);
					if (!sortedDictionary.ContainsKey(key))
					{
						sortedDictionary.Add(key, level);
					}
				}
				if (sortedDictionary.Count > 0)
				{
					outLevel = sortedDictionary.First<KeyValuePair<double, Level>>().Value;
					result = true;
				}
				else
				{
					outLevel = null;
				}
			}
			catch
			{
				outLevel = null;
			}
			return result;
		}

		public static bool GetTwoLevelProjDist(Level levelF, Level levelS, out double dDist, double dChange = 0.0)
		{
			bool result = false;
			dDist = 0.0;
			try
			{
				dDist = Math.Abs(levelF.ProjectElevation - levelS.ProjectElevation) + dChange;
			}
			catch (Exception)
			{
			}
			return result;
		}
	}
}
